// pages/order_detail/order_detail.js
const app = getApp();
import { u_formatTimestamp } from '../../config/tool.js';
import { seckill } from '../../utils/util.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '', // 订单id
    orderInfo: '', // 订单信息
    totalGoodsPrice: 0, // 商品总价
    times: '', // 倒计时
    schoolId: '', // 校区id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.id){
      this.setData({
        id: options.id
      })
    }
    if (options.schoolId){
      this.setData({
        schoolId: options.schoolId
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      totalGoodsPrice: 0
    })
    this.getData();
  },

  // 获取数据
  getData(){
    app.loading();
    let that = this;
    wx.request({
      url: app.baseURL + 'order/getOrderDetail',
      data: {
        token: app.globalData.userId,
        order_id: that.data.id,
        school_id: that.data.schoolId
      },
      success(data){
        let res = data.data;
        wx.hideLoading();
        if(res.code == 1){
          // 获取商品总价
          res.data.sub.forEach((item) =>{
            that.setData({
              totalGoodsPrice: (Number((Number(item.goods_price) * Number(item.total_num)).toFixed(2)) + Number(that.data.totalGoodsPrice)).toFixed(2)
            })
          })

          // 倒计时
          that.cutDown(res.data.count_down);

          // 改变时间格式
          if(res.data.createtime){
            res.data.createtime = u_formatTimestamp(res.data.createtime * 1000);
          }
          if (res.data.freight_time){
            res.data.freight_time = u_formatTimestamp(res.data.freight_time * 1000);
          }
          
          that.setData({
            orderInfo: res.data
          })
        }else{
          app.$tip(res.msg);
        }
      }
    })
  },

  formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },

  // 倒计时
  cutDown(time){
    let timmer = setInterval(() => {
      if (Number(time) > 0) {
        time--;
        this.setData({
          times: seckill(time)
        })
      } else {
        clearInterval(timmer)
      }
    }, 1000)
    this.setData({
      timmer: timmer
    })
  },

  // 订单支付
  toPay() {
    let that = this;
    app.loading();
    wx.request({
      url: app.baseURL + 'pay/pay',
      data: {
        token: app.globalData.userId,
        order_no: that.data.orderInfo.order_no,
        school_id: that.data.schoolId
      },
      success(data) {
        let res = data.data;
        if (res.code == 1) {
          that.wxPay(res.data);
        } else {
          wx.hideLoading();
          app.$tip(res.msg);
        }
      }
    })
  },

  // 微信支付
  wxPay(data) {
    let that = this;
    wx.requestPayment({
      timeStamp: data.timeStamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign,
      success(res) {
        wx.hideLoading();
        app.$tip('支付成功!');
        setTimeout(() => {
          that.getData();
        }, 1500)
      },
      fail(err) {
        wx.hideLoading();
        if (err.errMsg == 'requestPayment:fail cancel') {
          app.$tip('支付取消!');
        } else {
          app.$tip('支付失败!');
        }
      }
    })
  },

  // 取消订单
  cancelOrder() {
    let that = this;
    wx.showModal({
      title: '温馨提示',
      content: '您确定要取消当前订单吗?',
      confirmColor: '#5CA032',
      success(res) {
        if (res.confirm) {
          app.loading();
          wx.request({
            url: app.baseURL + 'order/setCancelOrder',
            data: {
              order_id: that.data.id,
              token: app.globalData.userId,
              school_id: that.data.schoolId
            },
            success(data) {
              let ress = data.data;
              wx.hideLoading();
              if (ress.code == 1) {
                app.$tip(ress.msg)
                setTimeout(() => {
                  that.getData();
                }, 1500)
              } else {
                app.$tip(ress.msg)
              }
            }
          })
        }
      }
    })
  },

  // 取消分享订单
  showRules() {
    wx.showModal({
      title: '暂时无法取消订单',
      content: '发起拼团24小时候，若未拼团成功 将自动取消订单并退款哦',
      confirmText: '我知道了',
      confirmColor: '#57b127',
      showCancel: false,
      success(res) {
        if (res.confirm) {

        }
      }
    })
  },

  // 删除订单
  delOrder() {
    let that = this;
    wx.showModal({
      title: '温馨提示',
      content: '您确定要删除当前订单吗?',
      confirmColor: '#5CA032',
      success(res) {
        if (res.confirm) {
          app.loading();
          wx.request({
            url: app.baseURL + 'order/setDelOrder',
            data: {
              order_id: that.data.id,
              token: app.globalData.userId,
              school_id: that.data.schoolId
            },
            success(data) {
              let ress = data.data;
              wx.hideLoading();
              if (ress.code == 1) {
                app.$tip(ress.msg)
                setTimeout(() => {
                  wx.navigateBack()
                }, 1500)
              } else {
                app.$tip(ress.msg)
              }
            }
          })
        }
      }
    })
  },

  // 立即提货
  toRecive(e) {
    if(this.data.schoolId){
      wx.navigateTo({
        url: '/pages/receiveCode/receiveCode?id=' + this.data.id + '&schoolId=' + this.data.schoolId,
      })
    }else{
      wx.navigateTo({
        url: '/pages/receiveCode/receiveCode?id=' + this.data.id,
      })
    }
  },

  // 查看物流
  toLook(e) {
    wx.navigateTo({
      url: '/pages/logistics/logistics?order_id=' + this.data.id,
    })
  },

  // 确认收货
  recived(e) {
    let that = this;
    wx.showModal({
      title: '温馨提示',
      content: '您确定要确认收货吗?',
      confirmColor: '#5CA032',
      success(res) {
        if (res.confirm) {
          app.loading();
          wx.request({
            url: app.baseURL + 'order/confirm_receipt',
            data: {
              order_id: that.data.id,
              token: app.globalData.userId,
              school_id: that.data.schoolId
            },
            success(data) {
              let ress = data.data;
              wx.hideLoading();
              if (ress.code == 1) {
                app.$tip(ress.msg)
                setTimeout(() => {
                  that.initData();
                  that.getData();
                }, 1500)
              } else {
                app.$tip(ress.msg)
              }
            }
          })
        }
      }
    })
  },

  // 拨打电话
  makeCall(){
    wx.makePhoneCall({
      phoneNumber: this.data.orderInfo.kf_phone,
      success(res){
        console.log(res)
      },
      fail(err){
        console.log(err)
      },
    })
  },

  // 去评价
  toEvaluate() {
    if(this.data.schoolId){
      wx.navigateTo({
        url: '/pages/pub_comment/pub_comment?id=' + this.data.id + '&schoolId=' + this.data.schoolId,
      })
    }else{
      wx.navigateTo({
        url: '/pages/pub_comment/pub_comment?id=' + this.data.id,
      })
    }
  },

  // 申请退款
  toRefound(){
    if (this.data.orderInfo.refund_status == 10){
      wx.showModal({
        title: '温馨提示',
        content: '已经有审核中的退款申请了,请等审核结束再申请吧!',
        showCancel: false,
        confirmColor: '#57b127',
        confirmText: '我知道了'
      })
      return
    }
    wx.navigateTo({
      url: '/pages/reback/reback?orderId=' + this.data.id,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.timmer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timmer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    // 来自页面内转发按钮
    if (res.from === 'button') {
      if (that.data.orderInfo.order_status == 60) {
        return {
          title: JSON.parse(wx.getStorageSync('userInfos')).username + '邀请您参与TA的拼团!',
          path: '/pages/waitJoin/waitJoin?actId=' + that.data.orderInfo.activity_id + '&goodsId=' + that.data.orderInfo.sub[0].goods_id,
          imageUrl: that.data.orderInfo.sub[0].image
        }
      } else {
        return {
          title: '华为全屋定制',
        }
      }
    }
    if (that.data.orderInfo.order_status == 60) {
      return {
        title: JSON.parse(wx.getStorageSync('userInfos')).username + '邀请您参与TA的拼团!',
        path: '/pages/waitJoin/waitJoin?actId=' + that.data.orderInfo.activity_id + '&goodsId=' + that.data.orderInfo.sub[0].goods_id,
        imageUrl: that.data.orderInfo.sub[0].image
      }
    } else {
      return {
        title: '华为全屋定制',
      }
    }
  }
})